import storage from './storage.js';
import cookie from '../utils/cookie.js';
import { ACCESS_TOKEN } from '../config/index.js';

function getCookieOption(expires) {
  return {
    expires: Number.isFinite(expires) ? expires : 1,
    secure: false,
    sameSite: 'Lax',
  };
}

export function clearToken() {
  cookie.remove(ACCESS_TOKEN);
  storage.session.removeItem(ACCESS_TOKEN);
}

export function setToken(token, expires) {
  const option = getCookieOption(expires);
  cookie.set(ACCESS_TOKEN, token, option);
  storage.session.setItem(ACCESS_TOKEN, token);
}

export function getToken() {
  return cookie.get(ACCESS_TOKEN);
}

export function hasToken() {
  return !!getToken();
}
